<?php

namespace app\http\middleware;
use think\facade\Cookie;
use think\Controller;
use think\Db;

class Auth extends Controller
{
    public function handle($request, \Closure $next)
    {
        if(!Cookie::has('token'))
            return $this->error('用户未登录','/index/index/login');
        $decrypted_data = decryptCookie(Cookie::get('token'), config('app.key'));
        if ($decrypted_data) {
            $user = json_decode($decrypted_data,true);
            if(!$userInfo = Db::name('user')->where(['username'=>$user['username']])->find())
                return $this->error('用户不存在','/index/index/login');
            $request->userInfo = $userInfo;
        } else {
            return $this->error('用户登录异常','/index/index/login');
        }

        

        $this->assign('userInfo',$userInfo);
        return $next($request);
    }
}
